/**
 * Created by caiqyxyx on 2017/2/15.
 * 添加删除tab按钮及事件 2017 02 17
 * 优化ui 2017 02 17
 * 优化代码结构，优化执行速率  2017 02 17
 */
define(['jquery', 'durandal/app'], function ($, app) {
    var MainUIUtils = function (selector, _item_, _group_) {
        var that = this, _group = [], _item = [], menu = [], tabList = [];
        tabList.push({url:'baiduMap',div:$('#application-map'),active:true});
        var $mainBody = $('#layout-main-body');
        $.each(_group_, function (index, item) {
            var tmp = {};
            tmp["id"] = (0 - item.groupID) + "";//组别的id为负数，防止与item中的id冲突
            tmp["name"] = item.groupNameCh;
            tmp["parentId"] = "0";
            tmp["url"] = item.url;
            tmp["icon"] = "";
            tmp["order"] = item.displayOrder + "";
            tmp["isHeader"] = "1";
            _group.push(tmp);
        });
        $.each(_item_, function (index, item) {
            var tmp = {};
            tmp["id"] = item.navID + "";
            tmp["name"] = item.navNameCh;
            tmp["parentId"] = item.seniorID == -1 ? (0 - item.groupID) + "" : item.seniorID + "";
            tmp["url"] = item.url;
            tmp["icon"] = item.navIcon;
            tmp["order"] = item.displayOrder + "";
            tmp["isHeader"] = "0";
            _item.push(tmp);
        });

        that.init = function () {
            that.renderUI();
            that.bindUI(selector);
        };

        that.renderUI = function () {
            that.generateMenuJson(_group, _item);
            that.generateMenuHtmlAndAppend(menu, $(selector));
            $(selector + " > li").addClass("menu-item");
        };

        that.generateMenuJson = function (groupArr, itemArr) {
            $.each(groupArr, function (index, objG) {
                var item = [];
                $.each(itemArr, function (j, objI) {
                    if (objI.parentId == objG.id) {
                        objI["childMenus"] = that.getChildren(itemArr, objI.id);
                        item.push(objI);
                    }
                });
                objG["childMenus"] = item;
                menu.push(objG);
            });
        };

        that.getChildren = function (arr, id) {
            var tmp = [];
            $.each(arr, function (index, item) {
                if (item.parentId == id) {
                    item["childMenus"] = that.getChildren(arr, item.ID);
                    tmp.push(item);
                }
            });
            return tmp;
        };

        that.generateMenuHtmlAndAppend = function (menu, parent) {
            $.each(menu, function (index, item) {
                var str = "";
                try {
                    if (item.isHeader == "1") {
                        str = "<li class='menu-header'>" + item.name + "</li>";
                        $(parent).append(str);
                        if (item.childMenus != "") {
                            that.generateMenuHtmlAndAppend(item.childMenus, parent);
                        }
                    } else {
                        item.icon == "" ? item.icon = "icon-leaf" : item.icon;
                        if (item.childMenus == "") {
                            str = "<li data-url = '" + item.url + "'><a><i class='" + item.icon + "'></i><span>" + item.name + "</span></a></li>";
                            $(parent).append(str);
                        } else {
                            str = "<li><a><i class='" + item.icon + "'></i><span>" + item.name + "</span><i class='icon-caret-right pull-right'></i></a>";
                            str += "<ul class='menu-item-child' id='menu-child-" + item.id + "'></ul></li>";
                            $(parent).append(str);
                            var childParent = $("#menu-child-" + item.id);
                            that.generateMenuHtmlAndAppend(item.childMenus, childParent);
                        }
                    }
                } catch (e) {
                }
            });
        };

        that.bindUI = function (selector) {
            var bindFunction = {
                leftBtnFun: function () {
                    var ml = Math.abs(parseInt($(".tab-nav-content").css("margin-left")));
                    var other_width = that.tabWidth($(".layout-main-tab").children().not(".tab-nav"));
                    var navWidth = $(".layout-main-tab").outerWidth(true) - other_width;//可视宽度
                    var hidewidth = 0;
                    if ($(".tab-nav-content").width() < navWidth) {
                        return false
                    } else {
                        var tabIndex = $(".content-tab:first");
                        var n = 0;
                        while ((n + $(tabIndex).outerWidth(true)) <= ml) {
                            n += $(tabIndex).outerWidth(true);
                            tabIndex = $(tabIndex).next();
                        }
                        n = 0;
                        if (that.tabWidth($(tabIndex).prevAll()) > navWidth) {
                            while ((n + $(tabIndex).outerWidth(true)) < (navWidth) && tabIndex.length > 0) {
                                n += $(tabIndex).outerWidth(true);
                                tabIndex = $(tabIndex).prev();
                            }
                            hidewidth = that.tabWidth($(tabIndex).prevAll());
                        }
                    }
                    $(".tab-nav-content").animate({marginLeft: 0 - hidewidth + "px"}, "fast");
                },
                rightBtnFun: function () {
                    var ml = Math.abs(parseInt($(".tab-nav-content").css("margin-left")));
                    var other_width = that.tabWidth($(".layout-main-tab").children().not(".tab-nav"));
                    var navWidth = $(".layout-main-tab").outerWidth(true) - other_width;//可视宽度
                    var hidewidth = 0;
                    if ($(".tab-nav-content").width() < navWidth) {
                        return false
                    } else {
                        var tabIndex = $(".content-tab:first");
                        var n = 0;
                        while ((n + $(tabIndex).outerWidth(true)) <= ml) {
                            n += $(tabIndex).outerWidth(true);
                            tabIndex = $(tabIndex).next();
                        }
                        n = 0;
                        while ((n + $(tabIndex).outerWidth(true)) < (navWidth) && tabIndex.length > 0) {
                            n += $(tabIndex).outerWidth(true);
                            tabIndex = $(tabIndex).next()
                        }
                        hidewidth = that.tabWidth($(tabIndex).prevAll());
                        if (hidewidth > 0) {
                            $(".tab-nav-content").animate({marginLeft: 0 - hidewidth + "px"}, "fast");
                        }
                    }
                },
                navChange: function () {
                    if (!$(this).hasClass("active")) {
                        var key = $(this).data("url");
                        $(this).addClass("active").siblings(".content-tab").removeClass("active");
                        //app.setRoot(key, null, 'applicationSubSystem');
                        $mainBody.find('.app-box-container').css('display', 'none');
                        $.each(tabList,function(_i_,_obj_){
                            if(_obj_.url == key){
                                _obj_.div.css('display','block');
                            }
                        });
                    }
                    that.addTab(this);
                },
                closeTab: function () {
                    var url = $(this).parents(".content-tab").data("url");
                    var cur_width = $(this).parents(".content-tab").width();
                    if ($(this).parents(".content-tab").hasClass("active")) {
                        if ($(this).parents(".content-tab").next(".content-tab").size()) {
                            var next_url = $(this).parents(".content-tab").next(".content-tab:eq(0)").data("url");
                            $(this).parents(".content-tab").next(".content-tab:eq(0)").addClass("active");
                            //app.setRoot(next_url, null, 'applicationSubSystem');
                            $mainBody.find('.app-box-container').css('display', 'none');
                            $.each(tabList,function (_i_,_obj_) {
                               if(_obj_.url == next_url){
                                   _obj_.div.css('display','block');
                                   _obj_.active = true;
                               }else{
                                   _obj_.active = false;
                               }
                            });
                            var n = parseInt($(".tab-nav-content").css("margin-left"));
                            if (n < 0) {
                                $(".tab-nav-content").animate({
                                        marginLeft: (n + cur_width) + "px"
                                    },
                                    "fast")
                            }
                            $(this).parents(".content-tab").remove();
                        }
                        if ($(this).parents(".content-tab").prev(".content-tab").size()) {
                            var prev_url = $(this).parents(".content-tab").prev(".content-tab:last").data("url");
                            $(this).parents(".content-tab").prev(".content-tab:last").addClass("active");
                            //app.setRoot(prev_url, null, 'applicationSubSystem');
                            $mainBody.find('.app-box-container').css('display', 'none');
                            $.each(tabList,function (_i_,_obj_) {
                                if(_obj_.url == prev_url){
                                    _obj_.div.css('display','block');
                                    _obj_.active = true;
                                }else{
                                    _obj_.active = false;
                                }
                            });
                            $(this).parents(".content-tab").remove();
                        }
                    } else {
                        $(this).parents(".content-tab").remove();
                        that.addTab($(".content-tab.active"))
                    }

                    var tmp = [];
                    $.each(tabList, function (_i_, _obj_) {
                         if(_obj_.url != url){
                             tmp.push(_obj_);
                         }else{
                             _obj_.div.remove();
                         }
                     });
                    tabList = tmp;
                    return false
                },
                openUrl: function (tar) {
                    var parentLi = tar.parent('li');
                    var url = parentLi.data('url');
                    var label = tar.text();
                    var tabExisted = false;
                    if (url) {
                        $.each(tabList, function (_i_, _obj_) {
                            if (_obj_.url == url) {
                                tabExisted = true;
                            }
                        });
                        if (tabExisted) {
                            var activedLabel = $(".tab-nav-content").find('.active:eq(0)').text();
                            if (activedLabel != label) {
                                $(".content-tab").each(function (ij, node) {
                                    if ($(this).data("url") == url) {
                                        $(this).addClass("active").siblings(".content-tab").removeClass("active");
                                    }
                                });
                                $mainBody.find('.app-box-container').css('display', 'none');
                                $.each(tabList,function(_i_,_obj_){
                                    if(_obj_.url == url){
                                        _obj_.div.css('display','block');
                                        _obj_.active = true;
                                    }else{
                                        _obj_.active = false;
                                    }
                                });
                                //app.setRoot(url, null, 'applicationSubSystem');
                            }
                        } else {
                            //tabList.push(url);
                            var _tab_ = "<a class='content-tab active' data-url='" + url + "' >" + label + " <i class='icon-remove'></i></a>";
                            $(".content-tab").removeClass("active");
                            $(".tab-nav-content").append(_tab_);
                            that.addTab($(".content-tab.active"));
                            var _id_ = url.upgradeUrl();
                            var _div = [];
                            _div.push('<div id="application-' + _id_ + '" class="app-box-container"><div class="cy-spinner"><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div></div>');
                            $div = $(_div.join(''));
                            $mainBody.append($div);
                            tabList.push({url:url,div:$div,active:true});
                            app.setRoot(url, null, 'application-' + _id_);
                            $mainBody.find('.app-box-container').css('display', 'none');
                            $div.css('display', 'block');
                        }
                    }
                }
            };
            /*左侧菜单点击*/
            $(selector).delegate('li a', 'click', function (e) {
                var animationSpeed = 300;
                var $this = $(this);
                var checkElement = $this.next();
                if (checkElement.is('.menu-item-child') && checkElement.is(':visible')) {
                    checkElement.slideUp(animationSpeed, function () {
                        checkElement.removeClass('menu-open');
                    });
                    checkElement.parent("li").removeClass("active");
                }
                //如果菜单是不可见的
                else if ((checkElement.is('.menu-item-child')) && (!checkElement.is(':visible'))) {
                    //获取上级菜单
                    var parent = $this.parents('ul').first();
                    //从父级开始找所有打开的菜单并关闭
                    var ul = parent.find('ul:visible').slideUp(animationSpeed);
                    //在父级中移出menu-open标记
                    ul.removeClass('menu-open');
                    //获取父级li
                    var parent_li = $this.parent("li");
                    //打开菜单时添加menu-open标记
                    checkElement.slideDown(animationSpeed, function () {
                        //添加样式active到父级li
                        checkElement.addClass('menu-open');
                        parent.find('li.active').removeClass('active');
                        parent_li.addClass('active');
                    });
                }
                //防止有链接跳转
                e.preventDefault();
                bindFunction.openUrl($this);
            });

            /*左按钮事件*/
            $(".btn-left").on("click", bindFunction.leftBtnFun);
            /*右按钮事件*/
            $(".btn-right").on("click", bindFunction.rightBtnFun);
            /*选项卡切换事件*/
            $(".tab-nav-content").delegate(".content-tab", "click", bindFunction.navChange);
            /*选项卡关闭事件*/
            $(".tab-nav-content").delegate(".content-tab i", "click", bindFunction.closeTab);
            /*选项卡双击关闭事件*/
            $(".tab-nav-content").delegate(".content-tab", "dblclick", function (e) {
                $(this).find('.icon-remove')[0].click();
            });
        };

        that.tabWidth = function (tabarr) {
            var allwidth = 0;
            $(tabarr).each(function () {
                allwidth += $(this).outerWidth(true);
            });
            return allwidth;
        };

        that.addTab = function (cur) {
            var prev_all = that.tabWidth($(cur).prevAll()),
                next_all = that.tabWidth($(cur).nextAll());
            var other_width = that.tabWidth($(".layout-main-tab").children().not(".tab-nav"));
            var navWidth = $(".layout-main-tab").outerWidth(true) - other_width;//可视宽度
            var hidewidth = 0;
            if ($(".tab-nav-content").width() < navWidth) {
                hidewidth = 0
            } else {
                if (next_all <= (navWidth - $(cur).outerWidth(true) - $(cur).next().outerWidth(true))) {
                    if ((navWidth - $(cur).next().outerWidth(true)) > next_all) {
                        hidewidth = prev_all;
                        var m = cur;
                        while ((hidewidth - $(m).outerWidth()) > ($(".tab-nav-content").outerWidth() - navWidth)) {
                            hidewidth -= $(m).prev().outerWidth();
                            m = $(m).prev()
                        }
                    }
                } else {
                    if (prev_all > (navWidth - $(cur).outerWidth(true) - $(cur).prev().outerWidth(true))) {
                        hidewidth = prev_all - $(cur).prev().outerWidth(true)
                    }
                }
            }
            $(".tab-nav-content").animate({marginLeft: 0 - hidewidth + "px"}, "fast")
        };
    };


    return {
        initUI: function (selector, item, group) {
            var instance = new MainUIUtils(selector, item, group);
            return instance.init();
        }
    }
});
